package nextel.visita.mvc;

import com.nextel.gui.gauge.FrmGaugeProcesar;
import com.nextel.gui.gauge.Procesar;
import com.nextel.ui.OHandset;
import java.io.ByteArrayOutputStream;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import nextel.Configuracion;
import nextel.visita.ControlVisita;
import nextel.visita.bean.FotoBean;
import pe.com.nextel.idioma.IdiomaManager;


/**
 *
 * @author eespinoza
 */
public class MVCFoto implements CommandListener, Procesar  {
    
    
    private VideoControl videoControl;
    private Player player;
    private Video video;
    private byte[] dataImg;
    private VideoCanvas canvas;
    private FormularioCanvas formCanvas;
    private Command cmdTomar,cmdGrabarFoto,cmdCancelFoto, cmdAtras,cmdCamara;
    private boolean flagDobleClick; // para que no presione dos veces al momento de buscar
    
    
    public void showScreen() throws Exception {
        
        
        cmdTomar = new Command(IdiomaManager.getInstance().getMensaje(IdiomaManager.JAVA_TOMAR), Command.OK, 1);
        cmdGrabarFoto = new Command(IdiomaManager.getInstance().getMensaje(IdiomaManager.JAVA_GRABAR), Command.OK, 2);
        cmdCancelFoto = new Command(IdiomaManager.getInstance().getMensaje(IdiomaManager.JAVA_CANCELAR), Command.CANCEL, 3);
        cmdAtras = new Command(IdiomaManager.getInstance().getMensaje(IdiomaManager.JAVA_ATRAS), Command.SCREEN, 5);
        
        flagDobleClick = true;
        
        showCamera();
        
    }
    
    
    public void showCamera( )throws Exception {
        
        player = Manager.createPlayer("capture://video");//Configuracion.VPLAYER
        player.realize();
        
        videoControl = (VideoControl)player.getControl("VideoControl");
        
        canvas = new VideoCanvas(videoControl);
        removeCommands();
        canvas.setCommandListener(this);
        flagDobleClick = true;
        canvas.addCommand(cmdTomar);
        canvas.addCommand(cmdAtras);
        
        OHandset.getDisplay().setCurrent(canvas);
        
        player.start();
        
    }
    
    public void commandAction(Command c, Displayable s) {
        
        if (flagDobleClick) {
            try {
                if (c == cmdTomar) {
                    flagDobleClick = false;
                    new FrmGaugeProcesar(this);
                } else if (c == cmdCancelFoto) {
                    flagDobleClick = true;
                } else if (c == cmdGrabarFoto) {
                    
                    flagDobleClick = false;
                    
                    if(ControlVisita.getInstance().currentServicio.numeroFoto < 3){
                        //System.out.println("menor a tres ");
                        FotoBean foto = new FotoBean();
                        ControlVisita.getInstance().currentServicio.numeroFoto++;
                        foto.data = (dataImg);
                        ControlVisita.getInstance().grabarFoto(foto);
                        destroy();
                        ControlVisita.getInstance().setCurrent(ControlVisita.getInstance().mvcEstado);
//                    flagDobleClick = true;
                    }else{
                        //System.out.println("mayor a tres ");
                        destroy();
                        ControlVisita.getInstance().setCurrent(ControlVisita.getInstance().mvcEstado);
                        //ControlVisita.getInstance().showMensaje("M?s de 3 fotos no es permitido por estado.",ControlVisita.getInstance().mvcEstado);
                    }
                    
                } else if( c == cmdAtras ){
                    flagDobleClick = false;
                    destroy();
                    
                    //navegar a la pantalla adecuada
                    ControlVisita.getInstance().setCurrent(ControlVisita.getInstance().mvcEstado);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    protected void destroy() {
        
        videoControl = null;
        
        if(player != null){
            player.close();
            player = null;
        }
        
        formCanvas = null;
        
        canvas = null;
        
        
    }
    
    public void removeCommands(){
        try{
            if(canvas != null){
                canvas.removeCommand(cmdTomar);
                canvas.removeCommand(cmdGrabarFoto);
                canvas.removeCommand(cmdCancelFoto);
                canvas.removeCommand(cmdAtras);
            }
            
            if(formCanvas != null){
                formCanvas.removeCommand(cmdTomar);
                formCanvas.removeCommand(cmdGrabarFoto);
                formCanvas.removeCommand(cmdCancelFoto);
                formCanvas.removeCommand(cmdAtras);
            }
//        formCanvas.removeCommand(cmdCapture);
        }catch(Exception e){e.printStackTrace();}
    }
    
    
    
    class Video  {
        public CommandListener command;
        
        public void start() {
            captureVideo();
        }
        
        public void captureVideo() {
            try {
                
                dataImg = videoControl.getSnapshot(null);
                
                //  dataImg = getThumbFromFile(dataImg);
                
                Image image = Image.createImage(dataImg, 0, dataImg.length);
                
                formCanvas = new FormularioCanvas();
                
                formCanvas.setCommandListener(command);
                
                formCanvas.itemFoto = ControlVisita.getInstance().currentServicio.numeroFoto + 1;
                
                formCanvas.setImage( createThumbnail(image) );
                
                removeCommands();
                
                flagDobleClick = true;
                
                formCanvas.addCommand(cmdGrabarFoto);
                formCanvas.addCommand(cmdAtras);
                
                OHandset.getDisplay().setCurrent(formCanvas);
                
                player.close();
                player = null;
                videoControl = null;
                
            } catch (MediaException me) { me.printStackTrace();}
        }
        
        private Image createThumbnail(Image image) {
            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            
            int thumbWidth = 120;
            int thumbHeight = -1;
            
            if (thumbHeight == -1)
                thumbHeight = thumbWidth * sourceHeight / sourceWidth;
            
            Image thumb = Image.createImage(thumbWidth, thumbHeight);
            Graphics g = thumb.getGraphics();
            
            for (int y = 0; y < thumbHeight; y++) {
                for (int x = 0; x < thumbWidth; x++) {
                    g.setClip(x, y, 1, 1);
                    int dx = x * sourceWidth / thumbWidth;
                    int dy = y * sourceHeight / thumbHeight;
                    g.drawImage(image, x - dx, y - dy,
                            Graphics.LEFT | Graphics.TOP);
                }
            }
            
            return Image.createImage(thumb);
            
        }
    };
    
    public void realizarProceso() {
        video = new Video( );
        video.command = (this);
        video.start();
        
    }
    
    
//    public  byte[] getThumbFromFile(byte bytefileReader[]) {
//        // final int THUMB_MAX_SIZE = 16284; // Max Thumbnail size
//        
//        ByteArrayOutputStream tempByteArray = new ByteArrayOutputStream();
//        
//        // byte[] tempByteArray = new byte[THUMB_MAX_SIZE]; // how big
//        // can a thumb get.
//        //  byte[] bytefileReader = { 0 }; // lazy byte reader
////        byte firstByte, secondByte = 0;
//        // int currentIndex = 0;
//        int i=0;
//        try {
//            
////            str.read(bytefileReader);
////            firstByte = bytefileReader[0];
////
////            str.read(bytefileReader);
////            secondByte = bytefileReader[0];
//            i++;
//            //  if (isJPEG(firstByte, secondByte)) {
//            
//            byte rByte = 0;
//            do
//            {
//                
//                while (rByte != -1 && i < bytefileReader.length ) {
//                    //str.read(bytefileReader);
//                    rByte = bytefileReader[++i];
//                }
//                
//                //str.read(bytefileReader);
//                rByte = bytefileReader[++i];
//                
//            } while ( (rByte & 0xFF) != 0xD8  && i < bytefileReader.length ); // thumb
//            // starts
//            
//            // tempByteArray[currentIndex++] = -1;
//            // tempByteArray[currentIndex++] = rByte;
//            
//            tempByteArray.write((byte) -1);
//            tempByteArray.write(rByte);
//            
//            rByte = 0;
//            do
//            {
//                while (rByte != -1 && i < bytefileReader.length ) {
//                    //str.read(bytefileReader);
//                    //rByte = bytefileReader[0];
//                    rByte = bytefileReader[++i];
//                    // tempByteArray[currentIndex++]
//                    // = rByte;
//                    tempByteArray.write(rByte);
//                }
//                //str.read(bytefileReader);
//                //rByte = bytefileReader[0];
//                rByte = bytefileReader[++i];
//                // tempByteArray[currentIndex++] =
//                // rByte;
//                tempByteArray.write(rByte);
//            } while ((rByte & 0xFF) != 0xD9  && i < bytefileReader.length ); // thumb
//            // ends
//            
//            // byte[] thumbBytes = new byte[currentIndex-1];
//            // tempByteArray[currentIndex++] = -1;
//            tempByteArray.write((byte) -1);
//            tempByteArray.flush();
//            
//            // Image im = Image.createImage ( tempByteArray,
//            // 0, currentIndex-1);
//            // tempByteArray = null;
//            // return im;
//            //
//            
//            return tempByteArray.toByteArray();
//            // }
//            //str.close();
//        } catch (Exception ex) {
//            System.out.println(" getThumbFromFile(): "
//                    + ex.toString());
//        }
//        return null;
//    }
    
    
//    public Image getThumbFromFile(InputStream str,long fileSize) throws Exception {
//        
//        byte[] tempByteArray = new byte[THUMB_MAX_SIZE]; // how big can a thumb get.
//        byte[] bytefileReader = {0}; // lazy byte reader
//        byte firstByte,secondByte = 0;
//        int currentIndex = 0;
//        
//        int currByte = 0;
//        
//        try {
//            str.read(bytefileReader);
//            firstByte = bytefileReader[0];
//            str.read(bytefileReader);
//            secondByte = bytefileReader[0];
//            
//            currByte += 2;
//            
//            if (isJPEG(firstByte, secondByte)){
//                
//                byte rByte = 0;
//                do {
//                    while(rByte != -1 && currByte < fileSize) {
//                        str.read(bytefileReader);
//                        rByte = bytefileReader[0];
//                        currByte++;
//                    }
//                    
//                    str.read(bytefileReader);
//                    rByte = bytefileReader[0];
//                    currByte++;
//                    
//                    if(currByte > STOP_AT_BYTE) {
//                        return null;
//                    }
//                    
//                } while ( (rByte & 0xFF) != 0xD8 && currByte < fileSize); // thumb starts
//                
//                if(currByte >= fileSize) {
//                    return null;
//                }
//                
//                tempByteArray[currentIndex++] = -1;
//                tempByteArray[currentIndex++] = rByte;
//                rByte = 0;
//                
//                do {
//                    while (rByte != -1){
//                        str.read(bytefileReader);
//                        rByte = bytefileReader[0];
//                        tempByteArray[currentIndex++] = rByte;
//                    }
//                    
//                    str.read(bytefileReader);
//                    rByte = bytefileReader[0];
//                    tempByteArray[currentIndex++] = rByte;
//                } while ( (rByte & 0xFF) != 0xD9 ); // thumb ends
//                
//                tempByteArray[currentIndex++] = -1;
//                Image im = Image.createImage( tempByteArray, 0, currentIndex-1);
//                tempByteArray = null;
//                
//                return im;
//            }
//            str.close();
//        } catch(Exception ex){
//            throw ex;
//        }
    }
    
    class VideoCanvas extends Canvas {
        
        
        public VideoCanvas(  VideoControl videoControl) {
            int width = getWidth();
            int height = getHeight();
            
            videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
            try {
                videoControl.setDisplayLocation(2, 2);
                videoControl.setDisplaySize(width - 4, height - 4);
            } catch (MediaException me) {me.printStackTrace();}
            videoControl.setVisible(true);
        }
        
        
        public void paint(Graphics g) {
            int width = getWidth();
            int height = getHeight();
            
            g.setColor(255, 0, 0);
            g.drawRect(0, 0, width - 1, height - 1);
            g.drawRect(1, 1, width - 3, height - 3);
        }
        
    }
    
    class FormularioCanvas extends Canvas {
        private Image imagen;
        public int itemFoto;
        public FormularioCanvas(){};
        
        public void setImage(Image img){
            imagen = img;
        }
        
        public void paint(Graphics g) {
            int width = getWidth();
            int height = getHeight();
            
            g.setColor(255, 255, 255);
            g.fillRect(0, 0, getWidth(), getHeight());
            
            g.setColor(255, 0, 0);
            g.drawRect(0, 0, width - 1, height - 1);
            g.drawRect(1, 1, width - 3, height - 3);
            g.drawString(" Foto  # " + itemFoto , 10, 5, g.TOP|g.LEFT);
            g.drawLine(0, g.getFont().getHeight() + 5, getWidth() ,  g.getFont().getHeight()+5);
            
            
            g.setColor(255, 255, 255);
            
            if(imagen != null){
                g.drawImage(imagen, getWidth() / 2, getHeight()/6, Graphics.TOP | Graphics.HCENTER);
            }
        }
        
        
        
        
    }
